package com.vincent.sms;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {


    private TextView tvStatus;

    private HashMap<String, String> mSmsIds = new HashMap<>();
    public static final int PERMISSIONS_REQUEST_READ_SMS = 201;
    private TextView tvSmsList;
    private Button btnReadSms;
    private Button btnPer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        tvStatus = findViewById(R.id.tv_status);
        tvSmsList = findViewById(R.id.tv_sms_list);
        btnReadSms = findViewById(R.id.btn_read_sms);
        btnPer = findViewById(R.id.btn_permission);


        btnPer.setOnClickListener(v -> {
            requestPermissionSmsCode();
            DefaultSmsHelper.requestToBeDefaultSmsApp(this , 1000);
        });

        btnReadSms.setOnClickListener(v -> {
            loadInboxMessages();
        });

    }

    private void requestPermissionSmsCode() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_SMS , Manifest.permission.SEND_SMS , Manifest.permission.RECEIVE_SMS}, PERMISSIONS_REQUEST_READ_SMS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @androidx.annotation.NonNull String[] permissions, @androidx.annotation.NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_READ_SMS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以继续读取短信了
                Toast.makeText(this , "权限被授予，可以继续读取短信了" , Toast.LENGTH_SHORT).show();
            } else {
                // 权限被拒绝，提醒用户手动开启权限
                Toast.makeText(this , "权限被拒绝，提醒用户手动开启权限" , Toast.LENGTH_SHORT).show();
            }
        }
    }



    // MainActivity.java
    private void requestDefaultSmsApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
            startActivity(intent);
        }
    }

    // 检查当前状态
    public boolean isDefaultSmsApp() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT ||
                getPackageName().equals(Telephony.Sms.getDefaultSmsPackage(this));
    }

    // 使用系统短信数据库（推荐方式）
    private void sendSmsViaDatabase(String phoneNumber, String message) {
        ContentValues values = new ContentValues();
        values.put(Telephony.Sms.ADDRESS, phoneNumber);
        values.put(Telephony.Sms.BODY, message);
        values.put(Telephony.Sms.DATE, System.currentTimeMillis());
        values.put(Telephony.Sms.STATUS, Telephony.Sms.STATUS_PENDING);

        getContentResolver().insert(Telephony.Sms.Outbox.CONTENT_URI, values);
    }

    // 传统方式（需SEND_SMS权限）
    private void sendSmsDirect(String phoneNumber, String message) {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNumber, null, message, null, null);
    }


    // 查询收件箱
    private void loadInboxMessages() {
        Cursor cursor = getContentResolver().query(
                Telephony.Sms.Inbox.CONTENT_URI,
                null, // 所有列
                null, // 条件
                null, // 参数
                Telephony.Sms.Inbox.DEFAULT_SORT_ORDER // 排序
        );

        StringBuffer stringBuffer = new StringBuffer();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range") long date = cursor.getLong(cursor.getColumnIndex(Telephony.Sms.Inbox.DATE));
                @SuppressLint("Range") String address = cursor.getString(cursor.getColumnIndex(Telephony.Sms.Inbox.ADDRESS));
                @SuppressLint("Range") String body = cursor.getString(cursor.getColumnIndex(Telephony.Sms.Inbox.BODY));
                // 处理消息
                stringBuffer.append("date：").append(date).append("\n");
                stringBuffer.append("address：").append(address).append("\n");
                stringBuffer.append("body：").append(body).append("\n");

            }
            tvSmsList.setText(stringBuffer);
            cursor.close();
        }
    }
}